<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="login-title">登录</h2>
      <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.email"
              placeholder="用户名"
              size="large"
              :prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password_hash"
              type="password"
              placeholder="密码"
              size="large"
              :prefix-icon="Lock"
              show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              size="large"
              class="login-btn"
              :loading="loading"
              @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useloginUserStore } from '../store/loginUserInfo.js'
import axios from '../axiosInstance.js'

const router = useRouter()
const loginUserStore = useloginUserStore()

// 表单引用
const loginFormRef = ref()
const loading = ref(false)

// 登录表单
const loginForm = reactive({
  email: '',
  password_hash: ''
})

// 表单验证规则
const loginRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' }
  ],
  password_hash: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 登录处理
const handleLogin = async () => {
  // 表单验证
  if (!loginFormRef.value) return

  const valid = await loginFormRef.value.validate()
  if (!valid) return

  loading.value = true

  try {

    // 调用登录接口
    const response = await axios.post('/user/login', {
      email: loginForm.email,
      password_hash: loginForm.password_hash
    })

    if (response.data && response.data.code === 200) {
      // 登录成功后存储用户信息到store中
      const userData = response.data.data
      const Token=response.data.saTokenInfo

      // 更新store状态
      loginUserStore.user_id = userData.user_id || ''
      loginUserStore.username = userData.username || loginForm.username
      loginUserStore.email = userData.email || ''
      loginUserStore.avatar_url = userData.avatar_url || ''

      // 存储token信息
      if (Token) {
        loginUserStore.saTokenInfo = {
          ...loginUserStore.saTokenInfo,
          ...Token
        }
      }
      console.log('登录返回数据:', userData)
      console.log('Store更新后:', loginUserStore.saTokenInfo)

      ElMessage.success('登录成功')

      // 跳转到首页
      router.push('/chat/home')
    } else {
      ElMessage.error(response.data.message || '登录失败，请检查用户名和密码')
    }
  } catch (error) {
    console.error('登录错误:', error)
    if (error.response) {
      // 服务器返回错误状态
      ElMessage.error(error.response.data.message || `登录失败: ${error.response.status}`)
    } else if (error.request) {
      // 未收到响应
      ElMessage.error('网络连接异常，请检查网络设置')
    } else {
      // 其他错误
      ElMessage.error('登录过程出现错误')
    }
  } finally {
    loading.value = false
  }
}

</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.login-form {
  width: 100%;
}

.login-btn {
  width: 100%;
  margin-top: 10px;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-button) {
  border-radius: 6px;
}
</style>